package reqcache

import (
	"sync"
	"time"
)

var cache sync.Map

type info struct {
	reqId   string
	reqTime time.Time
}

func IsValid(reqId string) bool {

	v, ok := cache.Load(reqId)
	if ok {
		if v.(info).reqTime.After(time.Now()) {
			return false
		} else {
			v := info{
				reqId:   reqId,
				reqTime: time.Now().Add(10 * time.Second),
			}
			cache.Store(reqId, v)
			return true
		}

	} else {
		v := info{
			reqId:   reqId,
			reqTime: time.Now().Add(10 * time.Second),
		}
		cache.Store(reqId, v)
		return true
	}
}

func rg(key, value interface{}) bool {

	if false == value.(info).reqTime.After(time.Now()) {
		cache.Delete(key)
	}

	return true
}

func Init() {

	go func() {
		for {
			time.Sleep(5 * time.Second)
			cache.Range(rg)
		}
	}()

}
